﻿/*
Commerce by Onex – eCommerce software platform (www.ecommerce.byonex.com)
Copyright (C) 2008-2010 by Onex Group

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Text;


using ShopModel;

namespace ShopDAO
{
    public class PictureDAO
    {
        private string connectionString;

        public PictureDAO()
        {
            connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["csShop"].ConnectionString;
        }

        /// <summary>
        /// Usuwa pliki zdjęć (Removes picture files from the database)
        /// </summary>
        /// <param name="productID">Id produktu, dla którego usuwamy zdjęcia (Product id for which we remove picture.)</param>
        /// <returns>Zwraca 'true', jeśli operacja usuwania zakończona powodzeniem (Returns True jesli when removal succeeded.)</returns>
        public bool DeletePicturesFromDataBase(int productID)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand sqlCommand = connection.CreateCommand();



            sqlCommand.CommandText = "DeletePicturesFromDataBase";
            sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
            sqlCommand.Parameters.Add(new SqlParameter("@productID", productID));

            try
            {
                connection.Open();
                sqlCommand.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
                return false;
            }
            finally
            {
                connection.Close();
            }
            
        }

        /// <summary>
        /// Zapisuje plik zdjęcia w bazie danych (Saves photo file in the database.)
        /// </summary>
        /// <param name="picture">Objekt PictureInfo przechowujący informacje o zdjęciu (PictureInfo object storing information about the picture.)</param>
        /// <returns>Zwraca 'true', jeśli operacja zakończona powodzeniem (Returns True when operation succeeded.)</returns>
        public  bool SavePicture(ShopModel.PictureInfo picture)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand sqlCommand = connection.CreateCommand();

            sqlCommand.CommandText = "SavePicture";
            sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;

            sqlCommand.Parameters.Add(new SqlParameter("@picture_id", picture.PictureId));
            sqlCommand.Parameters.Add(new SqlParameter("@name", picture.Name));
            sqlCommand.Parameters.Add(new SqlParameter("@is_main", picture.IsMain));
            sqlCommand.Parameters.Add(new SqlParameter("@product_id", picture.ProductId));
            sqlCommand.Parameters.Add(new SqlParameter("@miniature_id", picture.Miniature.PictureId));
            sqlCommand.Parameters.Add(new SqlParameter("@miniature_name", picture.Miniature.Name));

            try
            {
                connection.Open();
                sqlCommand.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
                return false;
            }
            finally
            {
                connection.Close();
            }
        }

        /// <summary>
        /// Pobiera inforacje o zdjęciach dla produktu o podanym id (Gets information about the pictures for the product about the given id.)
        /// </summary>
        /// <param name="productId">Id Produktu (Product id.)</param>
        /// <returns>Lista objektów typu PictureInfo (PictureInfo object's list.)</returns>
        public  List<PictureInfo> GetPictures(int productId)
        {
            PictureInfo picture;
            List<PictureInfo> result = new List<PictureInfo>();
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand sqlCommand = connection.CreateCommand();



            sqlCommand.CommandText = "PictureForProduct";
            sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
            sqlCommand.Parameters.Add(new SqlParameter("@product_id", productId));

            try
            {
                connection.Open();
                SqlDataReader reader = sqlCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

                while (reader.Read())
                {
                    picture = new PictureInfo();
                    picture.Miniature = new PictureInfo();

                    picture.IsMain = (bool)reader["IsMain"];
                    picture.Name = reader["Name"].ToString();
                    picture.PictureId = (int)reader["IDpicture"];
                    picture.ProductId = (int)reader["ProductID"];
                    picture.Miniature.Name = reader["MiniatureName"].ToString();
                    picture.Miniature.PictureId = (int)reader["MiniatureID"];
                    picture.Miniature.ProductId = (int)reader["ProductID"];

                    result.Add(picture);
                }
                reader.Close();

                return result;
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
                return null;
            }
            finally
            {
                connection.Close();
            }
        }

        /// <summary>
        /// Usuwa zdjęci o podanym id (Removes photos for the product with given id.)
        /// </summary>
        /// <param name="pictureId">Id zdjęcaia które ma zostać usunięte (Product id for which photos are to be removed.)</param>
        /// <returns>True jeśli operacja zakończona sukcesem (True is operation succedemd.)</returns>
        public  bool RemovePicture(int pictureId)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand sqlCommand = connection.CreateCommand();

            sqlCommand.CommandText = "RemovePicture";
            sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;

            sqlCommand.Parameters.Add(new SqlParameter("@picture_id", pictureId));

            try
            {
                connection.Open();
                sqlCommand.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
                return false;
            }
            finally
            {
                connection.Close();
            }
        }

        /// <summary>
        /// Ustaw zdjęcie o podanym id jako główne (Sets as main photo, picture with given id.)
        /// </summary>
        /// <param name="pictureId">Id zdjęcaia kótre ma zostać ustawione jako główne (Picture id for setting as main.)</param>
        /// <returns>True jeśli operacja zakończona sukcesem (True is operation succedemd.)</returns>
        public  bool SetAsMainPicture(int pictureId)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand sqlCommand = connection.CreateCommand();

            sqlCommand.CommandText = "SetAsMainPicture";
            sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;

            sqlCommand.Parameters.Add(new SqlParameter("@picture_id", pictureId));

            try
            {
                connection.Open();
                sqlCommand.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
                return false;
            }
            finally
            {
                connection.Close();
            }
        }

        /// <summary>
        /// Pobiera informacje dla zdjęcia o podanym id(Downloads information about photos with given id.)
        /// </summary>
        /// <param name="pictureId">Id zdjęcia które pobrać (Photo id to be downloaded.)</param>
        /// <returns>True jeśli operacja zakończona sukcesem (True is operation succedemd.)</returns>
        public  PictureInfo GetPicture(int pictureId)
        {
            PictureInfo picture = new PictureInfo();
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand sqlCommand = connection.CreateCommand();



            sqlCommand.CommandText = "PictureById";
            sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
            sqlCommand.Parameters.Add(new SqlParameter("@product_id", pictureId));


            //SqlDataReader sqlR = sqlCommand.ExecuteReader();
            try
            {
                connection.Open();
                SqlDataReader reader = sqlCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

                if (reader.Read())
                {
                    picture.Miniature = new PictureInfo();

                    picture.IsMain = (bool)reader["IsMain"];
                    picture.Name = reader["Name"].ToString();
                    picture.PictureId = (int)reader["IDpicture"];
                    picture.ProductId = (int)reader["ProductID"];
                    picture.Miniature.Name = reader["MiniatureName"] != DBNull.Value ? reader["MiniatureName"].ToString() : string.Empty;
                    picture.Miniature.PictureId = reader["MiniatureID"] != DBNull.Value ? (int)reader["MiniatureID"] : -1;
                    picture.Miniature.ProductId = reader["ProductID"] != DBNull.Value ? (int)reader["ProductID"] : -1;
                }

                reader.Close();

            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex); 
            }
            finally
            {
                connection.Close();
            }
            return picture;

        }

        /// <summary>
        /// Pobiera głowne djęcie dla produktu o podanym id (Gets main photo for the chosen product.)
        /// </summary>
        /// <param name="productId">Id produktu dla którego pobrać główne zdjęcie (Product id for which main photo is downloaded.)</param>
        /// <returns>Objekt typu PictureInfo przechowujący informacje o zdjęciu (PictureInfo object storing information about photos.)</returns>
        public  PictureInfo MainPictureForProduct(int productId)
        {
            PictureInfo picture = new PictureInfo();
            picture.Miniature = new PictureInfo();

            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand sqlCommand = connection.CreateCommand();



            sqlCommand.CommandText = "MainPictureForProduct";
            sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
            sqlCommand.Parameters.Add(new SqlParameter("@product_id", productId));

            try
            {
                connection.Open();
                SqlDataReader reader = sqlCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

                if (reader.Read())
                {
                    picture.IsMain = (bool)reader["IsMain"];
                    picture.Name = reader["Name"].ToString();
                    picture.PictureId = (int)reader["IDpicture"];
                    picture.ProductId = (int)reader["ProductID"];
                    picture.Miniature.Name = reader["MiniatureName"].ToString();
                    picture.Miniature.PictureId = (int)reader["MiniatureID"];
                    picture.Miniature.ProductId = (int)reader["ProductID"];

                    reader.Close();
                    return picture;
                }
                else
                {
                    reader.Close();
                    return null;
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
                return null;
            }
            finally
            {
                connection.Close();
            }
        }
    }
}
